package com.hmall.trade.listener;

import cn.hutool.core.util.ObjUtil;
import com.hmall.common.Constants.MqConstants;
import com.hmall.common.mq.DelayMessageProcessor;
import com.hmall.trade.config.MultiDelayCheckMsg;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.hmall.common.Constants.MqConstants.*;

@Component
@Slf4j
public class PayStatusListener {
    @Autowired
    private IOrderService orderService ;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = PAY_SUCCESS_QUEUE, durable = "true"),
            exchange = @Exchange(name = PAY_EXCHANGE),
            key = PAY_SUCCESS_KEY
    ))
    public void paySuccess(Long payOrderId) {
        log.info("支付成功，开始处理业务逻辑");
        orderService.markOrderPaySuccess(payOrderId);
    }

    /**
     * 订单延迟队列接受，取消订单待支付状态
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = DELAY_EXCHANGE_NAME ,type = ExchangeTypes.TOPIC ,delayed = "true"),
            key = DELAY_ORDER_KEY
    ))
    public void cancelOrder(MultiDelayCheckMsg<Long> msg) {
        if (ObjUtil.isNull(msg) || ObjUtil.isEmpty(msg.getCoreMsgData())){
            return;
        }
        log.info("订单延迟队列接受，取消订单待支付状态");
        // 1.获取订单状态，是否为已支付
        Order order = orderService.getById(msg.getCoreMsgData());
        if (ObjUtil.isEmpty(order) || order.getStatus() == 2){
            return;
        }
        // 检测是否还有下一个延时时间段，如果有就继续发送
        if (msg.hasNextDelayTime()){
            rabbitTemplate.convertAndSend(
                    MqConstants.DELAY_EXCHANGE_NAME,
                    MqConstants.DELAY_ORDER_KEY,
                    msg,
                    DelayMessageProcessor.of(msg.pollNextDelayTime())
//                    DelayMessageProcessor2.of(msg)
            );
            return;
        }
        // 2.取消订单（修改状态，取消库存锁定）
        orderService.cancelOrder(msg.getCoreMsgData());
        log.info("订单取消成功");
    }
}
